'use strict'

const { group } = require('console');
const titbit = require('titbit');

const {cookie,session} = require('titbit-toolkit')

const app = new titbit({
    debug:true
})

app.use((new cookie()).mid())

//一定要在cookie之后，session是基于cookie的
app.use( (new session()).mid())

// app.use(async (c,next)=>{
//     if(c.headers['cookie']===undefined){
//         c.setHeader('set-cookie','key=123')
//     }
//     await next();
// })

app.use(async (c,next)=>{
    console.log('just for home')
    await next()
    //添加只针对home分组执行的中间件
},{group:'home'})
app.get('/',async c=>{
    c.res.body = 'success'
},{name:'首页',group:'home'})//①'home'给路由起名，②'@home'分组是home分组 ③{name:'首页',group:'home'}

app.get('/cookie',async c=>{
    c.res.body = c.headers['cookie'] || '还没有设置cookie'
})

app.get('/login',async c=>{
    c.res.body = `<!DOCTYPE html><html>
      <head>
        <meta charset='utf-8>
      </head>
      <body>
        <form action="/login" method="post">
          <input type="text" name="username">
          <input type="password" name="passwd">
          <input type="submit" value="Login">
        </form>
      </body>
    </html>`
})
app.post('/login',async c=>{
    let {username,passwd} = c.body

    if(username==='testuser' &&passwd==='123456'){
        c.setSession('is_login',true)
        //登录成功跳转到首页
        c.status(301)
        c.setHeader('Location','/')
    }else{
        //登录失败跳转回登录界面
        c.status(301)
        c.setHeader('Location','/login')
    }
})
app.run(1234);

//setsid node app.js服务不会退出
